package com.xq.service.shareding;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.sun.prism.shader.Solid_TextureYV12_AlphaTest_Loader;
import com.xq.entity.UserInfo;
import com.xq.mapper.UserInfoMapper;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;

@Service
public class TableShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Autowired
    private ApplicationContext applicationContext;


    public static Date date = null;
    static {
        try {
            date = DateUtils.parseDate("2021-05-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    @Override
    public String doSharding(Collection availableTargetNames, PreciseShardingValue shardingValue) {
        System.out.println(JSON.toJSONString("availableTargetNames:"+availableTargetNames));
        System.out.println(JSON.toJSONString("shardingValue:"+shardingValue));
        //StringBuffer tableName = new StringBuffer();
        //tableName.append(shardingValue.getLogicTableName()).append("_").append(ParaseShardingKeyTool.getYearAndMonth(shardingValue.getValue()));
        //Integer value = (Integer) shardingValue.getValue()%2;
        //String table = "t_user_"+value;
        UserInfoMapper userInfoMapper = applicationContext.getBean(UserInfoMapper.class);
        Integer userId = (Integer) shardingValue.getValue();
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        String table = "act_telephone_contact";
        if(userInfo.getCreateDate().after(date)){
            table = "act_telephone_contact_"+ DateUtil.format(userInfo.getCreateDate(),"yyyy_MM");
        }
        return table;
    }

}
